// mcp/index.js
const { Client } = require("@modelcontextprotocol/sdk/client/index.js");
const { StdioClientTransport } = require("@modelcontextprotocol/sdk/client/stdio.js");
const OpenAI = require("openai");


/**
 * MCP客户端Client
 */
class MCPClient {
    openai = null

    constructor() {

        // 初始化 OpenAI 客户端
        this.openai = new OpenAI({
            apiKey: "sk-fUlXbvaD9R3shYo036971c2640914506B58057C5D7D23a71",
            baseURL: "https://maas-api.cn-huabei-1.xf-yun.com/v1",
        });

        // 初始化 MCP 客户端
        this.client = new Client({
            name: "mcp-typescript-client",
            version: "1.0.0",
        });

        // 初始化消息和工具列表
        this.messages = [
            {
                role: "system",
                content: "你的名字是Koala，你是一个智能助手，可以帮助用户解决问题。",
            },
        ];
        this.availableTools = [];
    }

    async connectToServer(serverScriptPath) {
        const isPython = serverScriptPath.endsWith(".py");
        const isJs = serverScriptPath.endsWith(".js");
        if (!isPython && !isJs) {
            throw new Error("Server script must be a .py or .js file");
        }

        const command = isPython ? "python" : "node";
        const transport = new StdioClientTransport({
            command,
            args: [serverScriptPath],
        });

        // 建立连接
        await this.client.connect(transport);

        // 获取并转换可用工具列表
        const tools = (await this.client.listTools()).tools;
        this.availableTools = tools.map(tool => ({
            type: "function",
            function: {
                name: tool.name,
                description: tool.description,
                parameters: {
                    type: "object",
                    properties: tool.inputSchema.properties,
                    required: tool.inputSchema.required,
                },
            },
        }));

        console.log("\nConnected to server with tools:", tools.map(t => t.name));
    }

    async handleToolCalls(response, messages) {
        let current = response;
        let count = 0;

        // 持续处理 tool_calls
        while (current.choices[0].message.tool_calls) {
            // 打印 AI 内容（除第一次）
            if (current.choices[0].message.content && count > 0) {
                console.log("\n🤖 AI:", current.choices[0].message.content);
            }
            count++;

            for (const call of current.choices[0].message.tool_calls) {
                const toolName = call.function.name;
                const args = JSON.parse(call.function.arguments);

                console.log(`\n🔧 调用工具 ${toolName}`, args);

                // 执行工具
                const result = await this.client.callTool({
                    name: toolName,
                    arguments: args,
                });

                // 把 AI 回复和工具结果加入消息历史
                messages.push(current.choices[0].message);
                messages.push({
                    role: "tool",
                    tool_call_id: call.id,
                    content: JSON.stringify(result.content),
                });
            }

            // 再次调用 OpenAI
            current = await this.openai.chat.completions.create({
                model: process.env.OPENAI_MODEL,
                messages,
                tools: this.availableTools,
            });
        }

        return current;
    }

    async processQuery(query) {
        // 添加用户消息
        this.messages.push({ role: "user", content: query });

        // 初次调用 OpenAI
        let response = await this.openai.chat.completions.create({
            model: "xdeepseekv3",
            messages: this.messages,
            tools: this.availableTools,
        });

        // 打印 AI 内容
        if (response.choices[0].message.content) {
            console.log("\n🤖 AI:", response.choices[0].message.content);
        }

        // 如果有工具调用，则处理
        if (response.choices[0].message.tool_calls) {
            response = await this.handleToolCalls(response, this.messages);
        }

        // 保存最终消息
        this.messages.push(response.choices[0].message);
        return response.choices[0].message.content || "";
    }

    async cleanup() {
        await this.client.close();
    }
}

// 导出已实例化对象
const chatClient = new MCPClient();
module.exports = chatClient;
